<!-- 文字头像 -->
<template>
  <div class="flex as-vertical y-center is-unselectable">
    <div
      class="flex avatar-text y-center x-center my-4"
      :class="size"
      :style="avatarStyle()"
    >
      {{ avatarText() }}
    </div>
  </div>
</template>

<script>
import variables from '@/styles/variables.scss'
const sha1 = require('sha1')

export default {
  props: {
    name: {
      // 显示的文字
      type: String,
      require: true,
      default: ''
    },
    size: {
      // 尺寸
      type: String,
      require: false,
      default: 'medium' // medium normal
    }
  },

  data() {
    return {
      colorSet: [
        '#3761ee',
        'rgb(47,104,141)',
        'rgb(25,77,127)',
        'rgb(71,69,103)',
        'rgb(71,88,118)'
      ]
    }
  },
  computed: {},
  mounted() {},
  variables() {
    return variables
  },

  methods: {
    /**
     * 头像上要显示的文字
     */
    avatarText() {
      const name = this.name.trim()
      // 名字是中文，返回后两个字
      if (!name.match(/[a-zA-Z]/gi)) return name.substr(-2)
      // 名字包含洋文，返回第一个空格前的完整单词
      else {
        return name.includes(' ') ? name.substring(0, name.indexOf(' ')) : name // 如果没有空格则完全返回
      }
    },

    /**
     * 根据名称计算独有的头像颜色
     */
    avatarStyle() {
      const name = this.name.trim()
      console.log(name.length)
      const s = sha1(name).replace(/[^0-9]/gi, '')
      const colorIndex = (s.charAt(0) + s.charAt(1)) % this.colorSet.length
      return `background-color:${this.colorSet[colorIndex]};`
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.avatar-text {
  // 长文本不换行 ---
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  // 长文本不换行 ---
  border-radius: 9999px;
  color: white;
}

.normal {
  font-size: 0.9rem;
  width: 45px;
  height: 45px;
}

.medium {
  font-size: 1.4rem;
  width: 60px;
  height: 60px;
}

.mini {
  font-size: 0.6rem;
  width: 35px;
  height: 35px;
}
</style>
